<template>
  <div class="search">
    <Card>
      <Row>
        <Form ref="searchForm" :model="searchForm" inline :label-width="75" class="search-form">
          <Form-item label="活动名称" prop="name">
            <Input type="text" v-model="searchForm.name" placeholder="请输入活动名称" clearable style="width: 200px" />
          </Form-item>
          <Form-item label="活动状态">
            <Select v-model="searchForm.activityStatus" placeholder="请选择" clearable style="width: 200px">
              <Option value="null">全部</Option>
              <Option value="0">未开始</Option>
              <Option value="1">已开始</Option>
              <Option value="2">未启用</Option>
              <Option value="3">已启用</Option>
              <Option value="4">已结束</Option>
            </Select>
          </Form-item>
          <Form-item label="发布人类型">
            <Select v-model="searchForm.submitType" placeholder="请选择" clearable style="width: 200px">
              <Option value="0">平台</Option>
              <Option value="1">城市合伙人</Option>
            </Select>
          </Form-item>
          <Form-item label="审核状态">
            <Select v-model="searchForm.auditStatus" placeholder="请选择" clearable style="width: 200px">
              <Option value="0">未审核</Option>
              <Option value="1">待审核</Option>
              <Option value="2">城市合伙人/未通过</Option>
              <Option value="3">已通过</Option>
              <Option value="4">平台/未通过</Option>
            </Select>
          </Form-item>
          <Button @click="handleSearch" class="search-btn" type="primary" icon="ios-search">搜索</Button>
          <Button class="search-btn" type="primary" @click="handleReset">重置</Button>
        </Form>
      </Row>
      <Table :loading="loading" border :columns="columns" class="mt_10" :data="data" ref="table"></Table>
      <Row type="flex" justify="end" class="mt_10">
        <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10, 20, 50, 100]" size="small" show-total show-elevator show-sizer></Page>
      </Row>
    </Card>
    <!-- 参与活动 -->
    <Modal :title="modalTitle" v-model="detailFlag" :mask-closable="false" :closable='false' :width="1000" :styles="{ top: '30px' }">
      <Form ref="form" :model="form" :rules="ruleValidate" :label-width="100">
        <FormItem label="海报" required>
          <upload-pic-input v-model="form.posterUrl" style="width: 350px" placeholder="上传图片尺寸：750*300px"></upload-pic-input>
        </FormItem>
        <FormItem label="活动名称" prop="name">
          <div class="item">
            <Input v-model="form.name" placeholder="请输入活动名称" />
          </div>
        </FormItem>
        <FormItem label="报名时间" prop="registrationStartStopTime">
          <Date-picker type="datetimerange" format="yyyy-MM-dd HH:mm:ss" placeholder="选择报名日期和时间" v-model="form.registrationStartStopTime" style="width: 350px"></Date-picker>
        </FormItem>
        <FormItem label="活动时间" prop="activityStartStopTime">
          <Date-picker type="datetimerange" format="yyyy-MM-dd HH:mm:ss" placeholder="选择活动日期和时间" v-model="form.activityStartStopTime" style="width: 350px"></Date-picker>
        </FormItem>
        <FormItem class="form-item-view-el" label="投放区域" required>
          <RadioGroup type="button" button-style="solid" v-model="form.salesArea">
            <Radio title="全国投放" :label="0">
              <span>全国投放</span>
            </Radio>
            <Radio title="区域投放" :label="1">
              <span>区域投放</span>
            </Radio>
          </RadioGroup>
          <region v-if="form.salesArea=='1'" :addressId="morenregionId" @selected="selectedRegionSearch" style="width: 350px;margin-top:24px" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="handleCancel()" style="margin-left: 8px">取消</Button>
        <Button type="primary" @click="handleSubmit()">发布</Button>
      </div>
    </Modal>
  </div>
</template>


<script>
import {
  getActivityList,
  addActivity,
  delActivity,
  editActivity,
} from "@/api/activity.js"
import region from "@/views/lili-components/region-every"
import Cookies from "js-cookie"
import uploadPicInput from "@/views/my-components/lili/upload-pic-input"
export default {
  name: "goods-activities",
  components: {
    uploadPicInput,
    region
  },
  data () {
    return {
      morenregionId: '',// 默认地区
      userInfo: '',//用户信息
      loading: true, // 表单加载状态
      detailFlag: false,
      modalType: 0, // 添加或编辑标识
      modalTitle: "新增", // 添加或编辑标题
      searchForm: {
        // 请求参数
        pageNumber: 1,
        pageSize: 10,
        order: "desc",// 默认排序方式
        sort: "create_time", // 默认排序字段
        activityType: 0,
      },
      form: {
        memberId: "",
        name: "", //商家名称
        salesArea: 0,//投放区域
        name: '', //活动名称
        content: '',
        activityType: 0,//活动类型
        registrationStartStopTime: '',//报名起止时间
        activityStartStopTime: '',//活动起止时间
        posterUrl: '',
        regionId: '',
        launchArea: '',
      },
      EditObj: null,
      columns: [
        {
          type: 'index',
          title: '序号',
          width: 60,
          align: 'center'
        },
        {
          title: "提交人类型",
          key: "submitType",
          render: (h, params) => {
            return h(
              "div", {},
              params.row.submitType === '1' ? '城市合伙人' : params.row.submitType === '2' ? '商家' : "平台"
            )
          },
        },
        {
          title: "投放区域",
          key: "launchArea",
          render: (h, params) => {
            return h(
              "div", {},
              params.row.launchArea === null || params.row.salesArea === "0" ? '全国' : params.row.launchArea
            )
          },
        },
        {
          title: "活动名称",
          key: "name",
        },
        {
          title: "活动开始时间",
          minWidth: 40,
          key: "activityStartTime",
          tooltip: true,
        },
        {
          title: "活动结束时间",
          minWidth: 40,
          key: "activityEndTime",
          tooltip: true,
        },
        {
          title: "报名起止时间",
          key: "registrationStartStopTime",
          minWidth: 170,
          render: (h, params) => {
            return h(
              "div", {},
              params.row.registrationStartStopTime.join("—")
            )
          },
        },
        {
          title: "发布时间",
          align: "left",
          minWidth: 40,
          key: "createTime",
        },
        {
          title: "活动状态",
          key: "activityStatus",
          render: (h, params) => {
            if (params.row.activityStatus === '0') {
              return h(
                "Tag", {
                props: {
                  color: "blue",
                },
              },
                "未开始"
              )
            } else if (params.row.activityStatus === '1') {
              return h(
                "Tag", {
                props: {
                  color: "magenta",
                },
              },
                "已开始"
              )
            } else if (params.row.activityStatus === '2') {
              return h(
                "Tag", {
                props: {
                  color: "green",
                },
              },
                "未启用"
              )
            } else if (params.row.activityStatus === '3') {
              return h(
                "Tag", {
                props: {
                  color: "volcano",
                },
              },
                "已启用"
              )
            } else {
              return h(
                "Tag", {
                props: {
                  color: "red",
                },
              },
                "已结束"
              )
            }
          },
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          width: 200,
          fixed: "right",
          render: (h, params) => {
            return h(
              "div",
              {
                style: {
                  display: "flex",
                  justifyContent: "center",
                },
              },
              [
                h(
                  "Button", {
                  props: {
                    type: "info",
                    size: "small",
                    ghost: true,
                  },
                  style: {
                    marginRight: "5px",
                    display: (params.row.activityStatus == '1') ? 'inline-block' : 'none',
                    disabled: (params.row.activityStatus == '1') ? true : false
                  },
                  on: {
                    click: () => {
                      this.edit(params.row)
                    },
                  },
                },
                  "参与活动"
                ),
                h(
                  "Button",
                  {
                    props: {
                      type: "info",
                      size: "small",
                    },
                    style: {
                      marginRight: "5px",
                    },
                    on: {
                      click: () => {
                        this.detail(params.row)
                      },
                    },
                  },
                  "活动详情"
                ),
                h(
                  "Button",
                  {
                    props: {
                      type: "info",
                      size: "small",
                    },
                    style: {
                      marginRight: "5px",
                      display: (params.row.activityStatus == '0' || params.row.activityStatus === '4') ? 'inline-block' : 'none'
                    },
                    on: {
                      click: () => {
                        this.del(params.row)
                      },
                    },
                  },
                  "修改详情"
                ),
              ]
            )
          },
        },
      ],
      data: [], // 活动数据
      total: 0, // 表单数据总数
      ruleValidate: {
        name: [
          { required: true, message: "活动名称不能为空", trigger: "blur" },
          { type: 'string', min: 3, max: 24, message: '长度为3~24之间', trigger: "blur" }
        ],
        registrationStartStopTime: [
          { required: true, type: 'array', min: 1, message: '请选择报名日期和时间', trigger: 'blur' }
        ],
        activityStartStopTime: [
          { required: true, type: 'array', min: 1, message: '请选择活动日期和时间', trigger: 'blur' }
        ]
      },
    }
  },
  created () {
    // 菜单初始化
    this.userInfo = JSON.parse(Cookies.get("userInfoManager"))
    if (this.userInfo.roles.length == 0) {
      this.columns = this.columns.filter(col => col.key !== 'auditStatus')
      this.columns = this.columns.filter(col => col.key !== 'remarks')
    }
  },
  methods: {
    // 选中的地址
    selectedRegionSearch (val) {
      this.form.launchArea = val[1].join(',')
      this.form.regionId = val[0].join(',')
    },
    dateFtt (fmt, date) {
      if (date) {
        //author: meizz
        var o = {
          "M+": date.getMonth() + 1, //月份
          "d+": date.getDate(), //日
          "h+": date.getHours(), //小时
          "m+": date.getMinutes(), //分
          "s+": date.getSeconds(), //秒
          "q+": Math.floor((date.getMonth() + 3) / 3), //季度
          S: date.getMilliseconds(), //毫秒
        }
        if (/(y+)/.test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length)
          )
        for (var k in o)
          if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length)
            )
        return fmt
      }
    },

    // 分页 改变页码
    changePage (v) {
      this.searchForm.pageNumber = v
      this.getData()
    },
    // 分页 改变页数
    changePageSize (v) {
      this.searchForm.pageSize = v
      this.searchForm.pageNumber = 1
      this.getData()
    },
    // 搜索
    handleSearch () {
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      this.getData()
    },
    handleReset () {
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      this.searchForm.name = ""
      this.searchForm.activityStatus = ''
      this.getData()
    },
    //查询商品活动列表
    getData () {
      getActivityList(this.searchForm).then((res) => {
        if (res.result.records) {
          this.loading = false
          this.data = res.result.records.map(item => {
            let registrationStartStopTime = []
            registrationStartStopTime.push(item.registrationStartTime, item.registrationEndTime)
            return {
              ...item,
              registrationStartStopTime
            }
          })
          this.total = res.result.total
        }
      })
    },
    // 新增活动+按钮
    addCredit () {
      this.modalType = 0
      this.modalTitle = "新建活动"
      this.detailFlag = true
      this.EditObj = {}
    },
    //编辑
    edit (row) {
      this.modalType = 1
      this.modalTitle = "编辑活动"
      this.detailFlag = true
      this.EditObj = {
        ...row,
      }
      this.form = {
        ...this.EditObj,
        registrationStartStopTime: [row.registrationStartTime, row.registrationEndTime],
        activityStartStopTime: [row.activityStartTime, row.activityEndTime],
        salesArea: Number(this.EditObj.salesArea)
      }

      if (this.EditObj.salesArea + '' === '1') {
        this.morenregionId = row.regionId
      }
    },
    // 发布
    handleSubmit (i) {
      let params = {
        name: this.form.name, //活动名称
        content: this.form.content,
        activityType: 0,//活动类型
        registrationStartTime: this.dateFtt("yyyy-MM-dd hh:mm:ss", this.form.registrationStartStopTime[0]),
        registrationEndTime: this.dateFtt("yyyy-MM-dd hh:mm:ss", this.form.registrationStartStopTime[1]),
        activityStartTime: this.dateFtt("yyyy-MM-dd hh:mm:ss", this.form.activityStartStopTime[0]),
        activityEndTime: this.dateFtt("yyyy-MM-dd hh:mm:ss", this.form.activityStartStopTime[1]),
        posterUrl: this.form.posterUrl,
        salesArea: this.form.salesArea,
        regionId: this.form.regionId,
        launchArea: this.form.launchArea
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.posterUrl == '') {
            this.$Message.error("请上传海报图片")
            return
          }
          if (this.form.registrationStartStopTime[0] == '') {
            this.$Message.error("报名日期和时间格式不正确")
            return
          }
          if (this.form.activityStartStopTime[0] == '') {
            this.$Message.error("活动日期和时间格式不正确")
            return
          }
          if (this.form.salesArea == 1) {
            if (this.form.regionId.length === 0) {
              this.$Message.error('请选投放区域')
              return
            }
          }
          if (this.form.content == '') {
            this.$Message.error("请输入活动说明")
            return
          }
          if (this.modalType === 0) {
            // 添加 避免编辑后传入id等数据 记得删除
            delete this.form.id
            addActivity(params).then((res) => {
              if (res.code == 200) {
                this.detailFlag = !this.detailFlag
                this.form = {
                  memberId: "",
                  name: "", //商家名称
                  salesArea: 0, // 投放区域
                  name: '', //活动名称
                  content: '',
                  activityType: 0,//活动类型
                  registrationStartStopTime: '',
                  activityStartStopTime: '',
                  posterUrl: '',
                  regionId: '',
                  region: '',
                }
                this.$Message.success(res.result)
                this.EditObj = {}
                this.$refs.form.resetFields()
                this.getData()
              } else {
                this.$Message.error("添加失败！")
              }
            })
          } else {
            // 编辑
            editActivity(this.form.id, params).then((res) => {
              if (res.success) {
                this.detailFlag = !this.detailFlag
                this.$refs.form.resetFields()
                this.getData()
                this.$Message.success("修改成功")
              } else {
                this.$Message.error("修改失败！")
              }
            })
          }
        } else {
          this.$Message.error("还有必填项未做处理，请检查表单")
        }
      })
    },
    // 取消事件
    handleCancel () {
      this.form = {
        memberId: "",
        name: "", //商家名称 
        salesArea: 0,// 投放区域
        name: '', //活动名称
        content: '',
        activityType: 0,//活动类型
        registrationStartStopTime: '',
        activityStartStopTime: '',
        posterUrl: '',
        regionId: '',
        region: '',
      }
      this.morenregionId = ''
      this.detailFlag = !this.detailFlag
      this.EditObj = {}
      this.$refs.form.resetFields()
    },
    del (row) {
      console.log('$%$$%%$$', row)
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除： " + row.name + "  该活动吗?",
        loading: true,
        onOk: () => {
          delActivity(row.id).then((res) => {
            this.$Modal.remove()
            if (res.success) {
              if (this.data.length == 1) {
                if (this.searchForm.pageNumber > 1) {
                  this.searchForm.pageNumber--
                }
              }
              this.$Message.success("删除成功")
              this.getData()
            }
          })
        },
      })
    },
    //查看详情
    detail (row) {
      this.$router.push({
        name: "activities-detail",
        query: {
          id: row.id,
          storeNum: row.storeNum,
        },
      })
    },
  },
  mounted () {
    this.getData()
  },
};
</script>
<style lang="scss">
@import '@/styles/table-common.scss';
.row Button {
  margin-right: 4px;
}
/deep/ .ivu-table-wrapper {
  width: 100%;
}

/deep/ .ivu-card {
  width: 100%;
}

.face {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}

.item {
  width: 350px !important;
  display: flex;

  > * {
    margin: 0 4px;
  }
}
</style>
